const path = require("path");
const webpack = require("webpack");
const { merge } = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");

const commonConfig = {
  entry: path.resolve(__dirname, "./src/main.js"),
  experiments: {
    outputModule: true
  },
  output: {
    filename: "markdown-editor.js",
    path: path.resolve(__dirname, "public"),
    library: {
      type: "module"
    }
  },
  resolve: {
    extensions: [".js", ".ts", ".vue", ".json"],
    alias: {
      "@": path.resolve(__dirname, "./src")
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
      {
        test: /\.(less|css)$/i,
        use: ["style-loader", "css-loader", "less-loader"]
      },

      {
        test: /\.(ttf|woff|woff2|png|svg)$/,
        loader: "url-loader"
      },
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        exclude: /node_modules/,
        options: {
          appendTsSuffixTo: [/\.vue$/]
        }
      }
    ]
  }
};

const devConfig = {
  devtool: "source-map",
  devServer: {
    contentBase: path.resolve(__dirname, "public"),
    host: "127.0.0.1",
    port: "8080",
    // port: 443,
    // https: true,
    open: true,
    proxy: {}
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      template: "./public/index.html", // Specify the path to your HTML file
      inject: false // You can change the injection location if needed
    }),
    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(false),
      VERSION: JSON.stringify("1.0.0")
    })
  ]
};

const prodConfig = {
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      template: "./public/index.html", // Specify the path to your HTML file
      inject: false // You can change the injection location if needed
    }),
    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(true),
      VERSION: JSON.stringify("1.0.0")
    })
  ]
};

module.exports = (env, argv) => {
  switch (argv.mode) {
    case "development":
      return merge(commonConfig, devConfig);
    case "production":
      return merge(commonConfig, prodConfig);
    default:
      throw new Error("No matched configuration was found!");
  }
};
